package com.smssalama.i18n;

import java.util.Hashtable;

import com.smssalama.SMSSalamaSession;

public class LocalizableFactory {
	private synchronized static Object doCreateLocalizedObject(Class clazz) {
		String locale = SMSSalamaSession.getSession().getLocale();
		locale = "_" + locale.replace('-', '_');
		while (locale.length() > 0) {
			String className = clazz.getName() + locale;
			try {
				Class resultClass = Class.forName(className);
				return resultClass.newInstance();
			} catch (ClassNotFoundException e) {
				// e.printStackTrace();
			} catch (InstantiationException e) {
				// e.printStackTrace();
			} catch (IllegalAccessException e) {
				// e.printStackTrace();
			}
			int lastIndex = locale.lastIndexOf('_');
			if (lastIndex > 0) {
				locale = locale.substring(0, lastIndex);
			} else {
				locale = "";
			}
		}
		try {
			return clazz.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
			throw new RuntimeException("Failed to instantiate class "
					+ clazz.getName());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new RuntimeException(
					"Access denied. Failed to instantiate class "
							+ clazz.getName());
		}
	}

	private static final Hashtable/* <Class, Object> */cache = new Hashtable();

	public synchronized static Object createLocalizedObject(Class clazz) {
		Object result = LocalizableFactory.cache.get(clazz);
		if (result == null) {
			result = LocalizableFactory.doCreateLocalizedObject(clazz);
			LocalizableFactory.cache.put(clazz, result);
		}
		return result;
	}

	public static void clearLocalizableCache() {
		LocalizableFactory.cache.clear();
	}

}
